//
//  AppDelegate.m
//  51易借
//
//  Created by 张睿 on 2017/8/17.
//  Copyright © 2017年 张睿. All rights reserved.
//

#import "AppDelegate.h"
#import "OrangeNavController.h"
#import "LoginViewController.h"
#import "MainViewController.h"
#import "AppDelegate+Timer.h"
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

#import <LocalAuthentication/LocalAuthentication.h>

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 启动图片延时: 3秒
//    [NSThread sleepForTimeInterval:3];
    
    [self runSystemTimer];
    [self loadData];
    
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]){
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
    
    // 2.注册极光推送
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    [JPUSHService setupWithOption:launchOptions appKey:@"9cd69508c6acbb94b35fd853"
                          channel:@"Publish channel"
                 apsForProduction:NO
            advertisingIdentifier:nil];
    
    // 接收应用内消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    // 极光推送登录成功后可以注册别名
//    [defaultCenter addObserver:self selector:@selector(registerAlias:) name:kJPFNetworkDidLoginNotification object:nil];
    
    
     self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
//    OrangeNavController * navVC = [[OrangeNavController alloc] initWithRootViewController:[LoginViewController new]];
    
    MainViewController * mainTab = [MainViewController new];
    
    self.window.rootViewController = mainTab;
    
//    self.window.rootViewController = navVC;
    
    
    [self.window makeKeyAndVisible];
    
   // [self deviceManagerTask];
    
//    //初始化上下文对象
//    LAContext* context = [[LAContext alloc] init];
//    //这个设置的使用密码的字体，当text=@""时，按钮将被隐藏
//    context.localizedFallbackTitle=@"";
//    //这个设置的取消按钮的字体
//    context.localizedCancelTitle=@"取消";
//    //错误对象
//    NSError* error = nil;
//    NSString* result = @"需要验证您的touch ID";
//    //首先使用canEvaluatePolicy 判断设备支持状态
//    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
//        //支持指纹验证
//        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
//            if (success) {
//                //验证成功，主线程处理UI
//                //NSLog(@"验证成功");
//            }
//            else
//            {
//                //NSLog(@"%@",error.localizedDescription);
//                switch (error.code) {
//                    case LAErrorSystemCancel:
//                    {
//                        //NSLog(@"Authentication was cancelled by the system");
//                        //切换到其他APP，系统取消验证Touch ID
//                        break;
//                    }
//                    case LAErrorUserCancel:
//                    {
//                        //NSLog(@"Authentication was cancelled by the user");
//                        //用户取消验证Touch ID
//                        break;
//                    }
//                    case LAErrorUserFallback:
//                    {
//                        //NSLog(@"User selected to enter custom password");
//                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                            //用户选择其他验证方式，切换主线程处理
//                        }];
//                        break;
//                    }
//                    default:
//                    {
//                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                            //其他情况，切换主线程处理
//                        }];
//                        break;
//                    }
//                }
//            }
//        }];
//    }
//    else
//    {
//        //不支持指纹识别，LOG出错误详情
//        switch (error.code) {
//            case LAErrorTouchIDNotEnrolled:
//            {
//                //NSLog(@"TouchID is not enrolled");
//                break;
//            }
//            case LAErrorPasscodeNotSet:
//            {
//                //NSLog(@"A passcode has not been set");
//                break;
//            }
//            default:
//            {
//                //NSLog(@"TouchID not available");
//                break;
//            }
//        }
//        //NSLog(@"%@",error.localizedDescription);
//    }
    
    return YES;
}

- (void)loadData{
    
    [[NetworkTool shareManager] POST:@"common/loadAllStaticPages.json" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            
            NSDictionary * data = responseObject[@"data"];
            
            
            DEF_SET_OBJECT(data[@"registerProtocol"],@"registerProtocol");
            DEF_SET_OBJECT(data[@"helpCenter"],@"helpCenter");
            DEF_SET_OBJECT(data[@"operatorAuthProtocol"],@"operatorAuthProtocol");
            DEF_SET_OBJECT(data[@"loanProtocol"],@"loanProtocol");
            DEF_SET_OBJECT(data[@"platformServiceProtocol"],@"platformServiceProtocol");
            DEF_SET_OBJECT(data[@"authDeductDelegate"],@"authDeductDelegate");
            DEF_SET_OBJECT(data[@"aboutCompany"],@"aboutCompany");
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"==%@",error);
        
    }];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
//    NSLog(@"已登录");
    if ([JPUSHService registrationID]) {
        
        //下面是我拿到registeID,发送给服务器的代码，可以根据你需求来处理
        NSString *registerid = [JPUSHService registrationID];
        
//        NSLog(@"APPDelegate开始上传rgeisterID");
        
       
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:registerid forKey:@"registerid"];
        
//        NSLog(@"*******get RegistrationID = %@ ",[JPUSHService registrationID]);
    }
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject: [JPUSHService registrationID] forKey:@"registrationID"];
    [defaults synchronize];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
//    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}





- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        
        [[UIApplication alloc] setApplicationIconBadgeNumber:0];
    }else{
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
        UIApplication *app = [UIApplication sharedApplication];
        // 应用程序右上角数字
        app.applicationIconBadgeNumber = 0;
    }
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [[UNUserNotificationCenter alloc] removeAllPendingNotificationRequests];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
